package cn.iocoder.yudao.module.handguard.service.usertablesaudit;

import cn.iocoder.yudao.framework.common.exception.ErrorCode;
import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.mybatis.core.query.LambdaQueryWrapperX;
import cn.iocoder.yudao.module.handguard.controller.app.usertablesaudit.vo.*;
import cn.iocoder.yudao.module.handguard.convert.usertablesaudit.UserTablesAuditConvert;
import cn.iocoder.yudao.module.handguard.dal.dataobject.applicationrecord.ApplicationRecordDO;
import cn.iocoder.yudao.module.handguard.dal.dataobject.order.OrderDO;
import cn.iocoder.yudao.module.handguard.dal.dataobject.orderprocessrecord.OrderProcessRecordDO;
import cn.iocoder.yudao.module.handguard.dal.dataobject.processrecord.ProcessRecordDO;
import cn.iocoder.yudao.module.handguard.dal.dataobject.userfollowup.UserFollowUpDO;
import cn.iocoder.yudao.module.handguard.dal.dataobject.usertablesaudit.UserTablesAuditDO;
import cn.iocoder.yudao.module.handguard.dal.mysql.applicationrecord.ApplicationRecordMapper;
import cn.iocoder.yudao.module.handguard.dal.mysql.order.OrderMapper;
import cn.iocoder.yudao.module.handguard.dal.mysql.orderprocessrecord.OrderProcessRecordMapper;
import cn.iocoder.yudao.module.handguard.dal.mysql.processrecord.ProcessRecordMapper;
import cn.iocoder.yudao.module.handguard.dal.mysql.publicitytype.PublicityTypeMapper;
import cn.iocoder.yudao.module.handguard.dal.mysql.userfollowup.UserFollowUpMapper;
import cn.iocoder.yudao.module.handguard.dal.mysql.usertablesaudit.UserTablesAuditMapper;
import cn.iocoder.yudao.module.handguard.service.matchinginfo.MatchingInfoService;
import cn.iocoder.yudao.module.handguard.service.notification.NotificationService;
import cn.iocoder.yudao.module.handguard.tool.DataConversionUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.framework.security.core.util.SecurityFrameworkUtils.getLoginUser;
import static cn.iocoder.yudao.module.handguard.enums.ErrorCodeConstants.*;

/**
 * 用户-完善资料记录 Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Validated
public class UserTablesAuditServiceImpl implements UserTablesAuditService {

    @Resource
    private NotificationService notificationService;

    @Resource
    private UserTablesAuditMapper userTablesAuditMapper;


    @Resource
    private PublicityTypeMapper publicityTypeMapper;

    @Resource
    private ApplicationRecordMapper applicationRecordMapper;

    @Resource
    private UserFollowUpMapper userFollowUpMapper;

    @Resource
    private OrderMapper orderMapper;

    @Resource
    private ProcessRecordMapper processRecordMapper;

    @Resource
    private OrderProcessRecordMapper orderProcessRecordMapper;

    @Resource
    private MatchingInfoService matchingInfoService;

    @Override
    @Transactional
    public String createUserTablesAudit(UserTablesAuditCreateReqsVO createReqVO) {
       createUserTablesAudits(createReqVO);
       return "";
    }

    /**
     * @Description: 后台管理使用
     * @Author: liuweijun
     * @Date: 2023/11/2
     * @Time: 16:04
     */
    @Override
    @Transactional
    public Long createUserTablesAudits(UserTablesAuditCreateReqsVO createReqVO) {
        //当前用户id
        Long userId = getLoginUser().getId();
        //先删除
        userTablesAuditMapper.deleteAllByOrderId(createReqVO.getOrderId(), createReqVO.getVoList().get(0).getTypeName());

        // 插入
        if (createReqVO.getVoList().size() > 0) {
            BigDecimal m = BigDecimal.ZERO;
            for (UserTablesAuditCreateReqVO reqsVO : createReqVO.getVoList()) {
                UserTablesAuditDO userTablesAudit = UserTablesAuditConvert.INSTANCE.convert(reqsVO);

                if (reqsVO.getCategory().equals("200")){
                    if (StringUtils.isEmpty(reqsVO.getParam1())){
                        ErrorCode MINI_PARAM_NULL_ERROR = new ErrorCode(1007700017, reqsVO.getCategoryName()+"不能为空");
                        throw exception(MINI_PARAM_NULL_ERROR);
                    }
                } else if (reqsVO.getCategory().equals("201")){
                    if (StringUtils.isEmpty(reqsVO.getParam1()) || StringUtils.isEmpty(reqsVO.getParam3())){
                        ErrorCode MINI_PARAM_NULL_ERROR = new ErrorCode(1007700017, reqsVO.getCategoryName()+"不能为空");
                        throw exception(MINI_PARAM_NULL_ERROR);
                    }
                }

                if (reqsVO.getCategory().equals("1")){
                    if (StringUtils.isEmpty(reqsVO.getResultValue())){
                        userTablesAudit.setResultValue("0");
                    }
                }

                //if (reqsVO.getCategoryName().equals("银行抵押月供") || reqsVO.getCategoryName().equals("银行按揭月供") ||
                //        reqsVO.getCategoryName().equals("银行信贷月供") || reqsVO.getCategoryName().equals("小贷公司月供") ||
                //        reqsVO.getCategoryName().equals("网贷月供")){
                //    m = m.add(new BigDecimal(reqsVO.getResultValue()));
                //}

                userTablesAuditMapper.insert(userTablesAudit);
            }

            //更新-整体负债月供
            //if (m.compareTo(BigDecimal.ZERO) > 0) {
            //    LambdaQueryWrapperX<UserTablesAuditDO> queryWrapperX = new LambdaQueryWrapperX<>();
            //    queryWrapperX.eq(UserTablesAuditDO::getOrderId,createReqVO.getOrderId());
            //    queryWrapperX.eq(UserTablesAuditDO::getCategoryName,"整体负债月供");
            //    UserTablesAuditDO auditDO = userTablesAuditMapper.selectOne(queryWrapperX);
            //    auditDO.setResultValue(m.toString());
            //    userTablesAuditMapper.updateById(auditDO);
            //}

        }

        //修改状态为跟进中
        ApplicationRecordDO app = new ApplicationRecordDO();
        app.setId(createReqVO.getOrderId());
        app.setApplyState("2");
        applicationRecordMapper.updateById(app);

        ApplicationRecordDO applicationRecordDO = applicationRecordMapper.selectById(createReqVO.getOrderId());


        //创建跟进记录，先删除再创建
        userFollowUpMapper.deleteByOrderId(createReqVO.getOrderId(), userId);
        UserFollowUpDO userFollowUpDO = new UserFollowUpDO();
        userFollowUpDO.setUserId(userId);
        userFollowUpDO.setFollowUpId(applicationRecordDO.getUserId());
        userFollowUpDO.setApplicationId(createReqVO.getOrderId());
        userFollowUpMapper.insert(userFollowUpDO);

        // 返回
        return createReqVO.getOrderId();
    }

    @Override
    @Transactional
    public void updateUserTablesAudit(UserTablesAuditUpdateReqVO updateReqVO) {
        //当前用户id
        Long userId = getLoginUser().getId();
        // 校验存在
        validateUserTablesAuditExists(updateReqVO.getItemList());

        //查询订单详情
        ApplicationRecordDO order = applicationRecordMapper.selectById(updateReqVO.getOrderId());

        //更新审核项
        if (updateReqVO.getIsPass() == 1) {
            LambdaQueryWrapper<UserTablesAuditDO> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(UserTablesAuditDO::getOrderId, updateReqVO.getOrderId());
            List<UserTablesAuditDO> list = userTablesAuditMapper.selectList(queryWrapper);
            userTablesAuditMapper.updateBatch(list.stream().filter(bean -> {
                bean.setIsPassed("1");
                return true;
            }).collect(Collectors.toList()));
        } else {
            if (updateReqVO.getItemList().size() > 0) {
                List<UserTablesAuditDO> updateObj = UserTablesAuditConvert.INSTANCE.convert(updateReqVO.getItemList());
                userTablesAuditMapper.updateBatch(updateObj.stream().filter(bean -> {
                    bean.setOrderId(updateReqVO.getOrderId());
                    bean.setIsPassed("0");
                    return true;
                }).collect(Collectors.toList()));
            } else {
                userTablesAuditMapper.updateByOrderId(order.getId(), "0");
            }
        }


        //删除当前流程审核记录，重新生成审核记录
        processRecordMapper.deleteProcessRecordById(updateReqVO.getOrderId());
        //完善资料未通过
        if (updateReqVO.getIsPass() == 0) {
            //如果选择项驳回
            ApplicationRecordDO recordDO = new ApplicationRecordDO();
            recordDO.setId(updateReqVO.getOrderId());
            recordDO.setFlowN("4");//退回业务员处理
            recordDO.setApplyState("1");//改为待跟进
            applicationRecordMapper.updateById(recordDO);

            //用户申请记录
            ProcessRecordDO processRecordDO = new ProcessRecordDO();
            processRecordDO.setUserId(order.getUserId());
            processRecordDO.setFlowN("4");
            processRecordDO.setIsFail("2");
            processRecordDO.setCauseOfFailure("权证驳回");
            processRecordDO.setApplicationId(updateReqVO.getOrderId());
            processRecordMapper.insert(processRecordDO);

        } else {
            //审核通过
            ProcessRecordDO processRecordDO = new ProcessRecordDO();
            processRecordDO.setUserId(order.getUserId());
            if (Integer.valueOf(order.getFlowN()) <= 6) {
                processRecordDO.setFlowN("7");
                processRecordDO.setIsFail("0");
            } else {
                processRecordDO.setFlowN(order.getFlowN());
                processRecordDO.setIsFail("0");
            }
            processRecordDO.setApplicationId(updateReqVO.getOrderId());
            processRecordMapper.insert(processRecordDO);

            //更新订单为跟进中
            order.setFlowN("7");
            order.setApplyState("2");
            applicationRecordMapper.updateById(order);
        }


        //创建跟进记录，先删除再创建
        userFollowUpMapper.deleteByOrderId(updateReqVO.getOrderId(), userId);
        UserFollowUpDO userFollowUpDO = new UserFollowUpDO();
        userFollowUpDO.setUserId(userId);
        userFollowUpDO.setFollowUpId(order.getUserId());
        userFollowUpDO.setApplicationId(updateReqVO.getOrderId());
        userFollowUpMapper.insert(userFollowUpDO);
    }

    @Override
    public void deleteUserTablesAudit(Long id) {
        // 校验存在
        validateUserTablesAuditExists(id);
        // 删除
        userTablesAuditMapper.deleteById(id);
    }

    private void validateUserTablesAuditExists(Long id) {
        if (userTablesAuditMapper.selectById(id) == null) {
            throw exception(USER_TABLES_AUDIT_NOT_EXISTS);
        }
    }

    private void validateUserTablesAuditExists(List<UserTablesAuditItemVO> item) {
        for (UserTablesAuditItemVO data : item) {
            //依次查询每一项，
            if (userTablesAuditMapper.selectCount("id", data.getId()) <= 0) {
                throw exception(USER_TABLES_AUDIT_NOT_EXISTS);
            }
        }
    }

    @Override
    public UserTablesAuditDO getUserTablesAudit(Long id) {
        return userTablesAuditMapper.selectById(id);
    }

    @Override
    public List<UserTablesAuditDO> getUserTablesAuditList(Collection<Long> ids) {
        return userTablesAuditMapper.selectBatchIds(ids);
    }

    @Override
    public List<UserTablesAuditDO> getUserTablesAuditList(Long orderId, String typeName) {
        LambdaQueryWrapperX<UserTablesAuditDO> queryWrapper = new LambdaQueryWrapperX<>();
        queryWrapper.eq(UserTablesAuditDO::getOrderId, orderId);
        queryWrapper.eq(UserTablesAuditDO::getTypeName, typeName);
        List<UserTablesAuditDO> doList = userTablesAuditMapper.selectList(queryWrapper);
        return doList;
    }

    @Override
    public List<UserTablesAuditDO> getUserTablesAuditList(Long orderId) {
        return userTablesAuditMapper.selectList(new LambdaQueryWrapper<UserTablesAuditDO>()
                .eq(UserTablesAuditDO::getOrderId, orderId));
    }

    @Override
    public PageResult<UserTablesAuditDO> getUserTablesAuditPage(UserTablesAuditPageReqVO pageReqVO) {
        return userTablesAuditMapper.selectPage(pageReqVO);
    }

    @Override
    public List<UserTablesAuditDO> getUserTablesAuditList(UserTablesAuditExportReqVO exportReqVO) {
        return userTablesAuditMapper.selectList(exportReqVO);
    }

    @Override
    public Map<String, List<UserTablesAuditDO>> getOrderDataList(Long id, int status) {
        LambdaQueryWrapper<UserTablesAuditDO> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserTablesAuditDO::getOrderId, id);
        if (status == 0) {
            wrapper.eq(UserTablesAuditDO::getIsPassed, status);
        }
        //wrapper.orderByAsc(UserTablesAuditDO::getTypeId,UserTablesAuditDO::getCreateTime);
        List<UserTablesAuditDO> list = userTablesAuditMapper.selectList(wrapper);
        if (list == null || list.size() == 0) {
            list = userTablesAuditMapper.getDefaultAudit();
        }
//        list.forEach(u->{
//            //公示表名称
//            PublicityTypeDO publicityTypeDO = publicityTypeMapper.selectById(u.getTypeId());
//            u.setTypeName(publicityTypeDO.getTypeNames());
//        });

        //分组数据
        Map<String, List<UserTablesAuditDO>> listMap = DataConversionUtils.groupByStream(list);

        return listMap;
    }

    @Override
    @Transactional
    public void updateUserTablesAudits(UserTablesAuditUpdateReqsVO updateReqVO) {

        List<UserTablesAuditDO> list = UserTablesAuditConvert.INSTANCE.convertList2(updateReqVO.getItemList());
        userTablesAuditMapper.updateBatch(list);

        //删除权证审核记录
        processRecordMapper.deleteProcessRecordById(updateReqVO.getOrderId());
    }

    @Override
    @Transactional
    public void updateApplicationAudit(UserAuditUpdateReqVO updateReqVO) {
        ApplicationRecordDO application = applicationRecordMapper.selectById(updateReqVO.getOrderId());
        //删除当前流程审核记录，重新生成审核记录
        processRecordMapper.deleteProcessRecordById(updateReqVO.getOrderId());

        //完善资料未通过-驳回
        ApplicationRecordDO recordDO = new ApplicationRecordDO();
        recordDO.setId(updateReqVO.getOrderId());
        recordDO.setFlowN("4");
        recordDO.setApplyState("0");
        applicationRecordMapper.updateById(recordDO);

        //用户申请记录
        ProcessRecordDO processRecordDO = new ProcessRecordDO();
        processRecordDO.setUserId(recordDO.getUserId());
        processRecordDO.setFlowN("4");
        processRecordDO.setIsFail("2");
        processRecordDO.setCauseOfFailure(updateReqVO.getRemark());
        processRecordDO.setApplicationId(updateReqVO.getOrderId());
        processRecordMapper.insert(processRecordDO);

        //发送驳回通知消息
        notificationService.sendOrderNotification(updateReqVO.getRemark(),"test008",application.getUserId());
    }


}
